//
//  BaseInterface.m
//  Sq
//
//  Created by mini00010 on 15/10/30.
//  Copyright (c) 2015年 mini00010. All rights reserved.
//

#import "BaseInterface.h"
//#import "DefineInterfaceUrl.h"
#import <AFNetworking.h>

#define plase_png [UIImage imageNamed:@"nothing1.png"]

@implementation BaseInterface

//请求服务器
+ (void)requestServerWithParameters:(NSMutableDictionary *)parameters URL:(NSString *)url withBlock:(void (^)(NSMutableDictionary *responseDic, NSError *error))block{

    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 12;//请求超时时间
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    
    url = [NSString stringWithFormat:@"%@%@",kBase_url,url];
    
    [manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        @try {
            if (responseObject) {
                if (block) {
                    block(responseObject, nil);
                }
            }
        }
        @catch (NSException *exception) {
            
        }

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
        if (block) {
            block(nil, error);
            NSLog(@"失败%@",error);
        }

        
    }];
    

}
+(void)requestServerWithParameters:(NSMutableDictionary *)parameters dataArr:(NSMutableArray *)mutableArr URL:(NSString *)url withBlock:(void (^)(NSMutableDictionary *, NSError *))block{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 60;//请求超时时间
    //    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"text/html", nil]];
    
    url = [NSString stringWithFormat:@"%@%@",kBase_url,url];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        
        if (mutableArr.count == 1) {
            NSString *temp =  [[[mutableArr objectAtIndex:0] allKeys] objectAtIndex:0];
            NSArray *arr_temp = [[mutableArr objectAtIndex:0] objectForKey:temp];
            for (int i = 0; i  <arr_temp.count; i ++) {
                
                @autoreleasepool {
                    
                    if ([temp isEqualToString:@"imagefile"]) {
                        
                        
                        
                        NSDate *  senddate=[NSDate date];
                        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
                        [dateformatter setDateFormat:@"hh:mm:ss:sss"];
                        NSString *  locationString=[[NSString stringWithFormat:@"%@%d.png", [dateformatter stringFromDate:senddate],i]stringByReplacingOccurrencesOfString:@":" withString:@""];
                        NSString *str = [NSString stringWithFormat:@"%@",arr_temp[i]];
                        
                        
                        if (![str isEqualToString:@""]) {
                            //                         UIImage *image = arr_temp[i];
                            //                         NSData *imagedata = UIImagePNGRepresentation(image);
                            NSData *imagedata = [self compressimage:arr_temp[i] TolimitByte:50*1024];
                            [formData appendPartWithFileData:imagedata name:[NSString stringWithFormat:@"fileName%d",i+1] fileName:locationString mimeType:@"multipart/form-data"];
                        }
                    }else{
                        NSDate *  senddate=[NSDate date];
                        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
                        [dateformatter setDateFormat:@"hh:mm:ss:sss"];
                        NSString *  locationString=[[NSString stringWithFormat:@"%@%d.mp4", [dateformatter stringFromDate:senddate],i]stringByReplacingOccurrencesOfString:@":" withString:@""];
                        //                     NSLog(@"%@",locationString);
                        NSData *data = [NSData dataWithContentsOfURL:[arr_temp objectAtIndex:i]];
                        if (data.length != 0) {
                            [formData appendPartWithFileData:data name:[NSString stringWithFormat:@"fileName%d",i+1] fileName:locationString mimeType:@"multipart/form-data"];
                        }
                    }
                    
                }
                
            }
        }
        
        if (mutableArr.count == 2) {
            NSArray *arr_image ;
            NSArray *arr_movie ;
            if ([[[[mutableArr objectAtIndex:0] allKeys] objectAtIndex:0] isEqualToString:@"imagefile"]) {
                arr_image = [[mutableArr objectAtIndex:0]objectForKey:@"imagefile"];
                arr_movie = [[mutableArr objectAtIndex:1]objectForKey:@"moviefile"];
            }else{
                arr_image = [[mutableArr objectAtIndex:1]objectForKey:@"imagefile"];
                arr_movie = [[mutableArr objectAtIndex:0]objectForKey:@"moviefile"];
            }
            
            int j = 0;
            for (; j < arr_image.count; j++) {
                
                @autoreleasepool {
                    NSDate *  senddate=[NSDate date];
                    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
                    [dateformatter setDateFormat:@"hh:mm:ss:sss"];
                    NSString *  locationString=[[NSString stringWithFormat:@"%@%d.png", [dateformatter stringFromDate:senddate],j]stringByReplacingOccurrencesOfString:@":" withString:@""];
                    NSLog(@"%@",locationString);
                    //                UIImage *image = arr_image[j];
                    //                NSData *imagedata = UIImagePNGRepresentation(image);
                    //           data = UIImageJPEGRepresentation(image, 1);
                    NSData *imagedata = [self compressimage:arr_image[j] TolimitByte:50*1024];
                    [formData appendPartWithFileData:imagedata name:[NSString stringWithFormat:@"fileName%d",j+1] fileName:locationString mimeType:@"multipart/form-data"];
                }
            }
            
            for (; j <arr_movie.count + arr_image.count; j ++) {
                
                @autoreleasepool {
                    
                    NSDate *  senddate=[NSDate date];
                    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
                    [dateformatter setDateFormat:@"hh:mm:ss:sss"];
                    NSString *  locationString=[[NSString stringWithFormat:@"%@%d.mp4", [dateformatter stringFromDate:senddate],j]stringByReplacingOccurrencesOfString:@":" withString:@""];
                    NSLog(@"%@",locationString);
                    NSData *data = [NSData dataWithContentsOfURL:[arr_movie objectAtIndex:j -arr_image.count]];
                    if (data.length != 0) {
                        [formData appendPartWithFileData:data name:[NSString stringWithFormat:@"fileName%d",j+1] fileName:locationString mimeType:@"multipart/form-data"];
                    }
                    
                }
                
            }
            
        }

        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        @try {
            if (responseObject) {
                if (block) {
                    block(responseObject, nil);
                }
            }
        }
        @catch (NSException *exception) {
            
        }

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (block) {
            block( nil, error);
            NSLog(@"失败%@",error);
        }

        
    }];
    

    
}


+(CAShapeLayer *)six:(float)with{
    float viewWidth = with;
    UIBezierPath * path = [UIBezierPath bezierPath];
    path.lineWidth = 2;
    [[UIColor whiteColor] setStroke];
    [path moveToPoint:CGPointMake(0, (viewWidth / 2))];
    [path addLineToPoint:CGPointMake(viewWidth/4, (sin(M_1_PI / 180 * 60)) * (viewWidth / 2))];
    [path addLineToPoint:CGPointMake((viewWidth / 2) + (viewWidth / 4),  (sin(M_1_PI / 180 * 60)) * (viewWidth / 2))];
    [path addLineToPoint:CGPointMake(viewWidth, viewWidth/2)];
    [path addLineToPoint:CGPointMake((viewWidth / 2) + (viewWidth / 4),viewWidth - ((sin(M_1_PI / 180 * 60)) * (viewWidth / 2)))];
    [path addLineToPoint:CGPointMake( (viewWidth / 4),viewWidth - ((sin(M_1_PI / 180 * 60)) * (viewWidth / 2)))];
    [path closePath];
    
    CAShapeLayer * shapLayer = [CAShapeLayer layer];
    shapLayer.lineWidth = 2;
    shapLayer.strokeColor = [UIColor whiteColor].CGColor;
    shapLayer.path = path.CGPath;
    return shapLayer;

}



+(NSData *)compressimage:(UIImage *)originalimage TolimitByte:(float)limitByte
{
    NSData *newImageData = nil;
    CGSize originalImageSize = originalimage.size;
    NSData *imgData =UIImageJPEGRepresentation(originalimage, 1.0);
    if (imgData.length > limitByte) {
        for (int i = 1; i <= 10; i++) {
            
            NSData *imgData =UIImageJPEGRepresentation(originalimage, 0.1*(10-i));
            if (imgData.length <= limitByte ) {
                newImageData = imgData;
                break;
            }
            
            if (i == 10) {
                if (imgData.length > limitByte){
                    
                    for (int i = 1; i <= 5; i++) {
                        UIImage *newImage = [self equalScaleCompressImage:[UIImage imageWithData:imgData] size:CGSizeMake(originalImageSize.width*(0.1*(10-i)), originalImageSize.height*(0.1*(10-i)))];
                        NSData *imgData =UIImageJPEGRepresentation(newImage, 0.1);
                        if (imgData.length <= limitByte) {
                            newImageData = imgData;
                            break;
                        }
                        if (i == 5) {
                            newImageData = imgData;
                        }
                    }
                    
                }
            }
        }
        
    }else{
        newImageData = imgData;
    }
    
    return newImageData;
}


+ (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize

{
    
    UIImage *newimage;
    
    if (nil == image)
    {
        
        newimage = nil;
        
    } else {
        
        CGSize oldsize = image.size;
        
        CGRect rect;
        
        if (asize.width/asize.height > oldsize.width/oldsize.height)
            
        {
            
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            
            rect.size.height = asize.height;
            
            rect.origin.x = (asize.width - rect.size.width)/2;
            
            rect.origin.y = 0;
            
        } else {
            
            rect.size.width = asize.width;
            
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            
            rect.origin.x = 0;
            
            rect.origin.y = (asize.height - rect.size.height)/2;
            
        }
        
        UIGraphicsBeginImageContext(asize);
        
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        
        [image drawInRect:rect];
        
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
        
    }
    
    return newimage;
    
}

+(UIImage *)equalScaleCompressImage:(UIImage *)sourceImage
                               size:(CGSize)imageSize{
    
    //    CGFloat width = sourceImage.size.width;
    //    CGFloat height = sourceImage.size.height;
    CGFloat targetWidth = imageSize.width;
    CGFloat targetHeight = imageSize.height;
    NSLog(@"%f  %f",targetWidth,targetHeight);
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0,0,targetWidth,  targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}
+(UIImageView *)stay_here:(UIView *)view_super hiden:(BOOL)is_hidden{
    UIImageView *imageView_here =  [[UIImageView alloc]initWithFrame:CGRectMake(0,100, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height/3)];
//    imageView_here.center = view_super.center;
//    imageView_here.backgroundColor = [UIColor redColor];
    imageView_here.image  = plase_png;
    imageView_here.contentMode = UIViewContentModeScaleAspectFit;
    imageView_here.hidden = is_hidden;
    return imageView_here;
}
+(NSString *)isvalue:(NSString *)value{
    if ([value isKindOfClass:[NSNull class]]) {
        return @"";
    }else if ([value isEqualToString:@""]){
        return @"";
    }else if (value ==nil){
        return @"";
    }else{
        return value;
    }
}
+(CGFloat)Someone_image_height:(UIImageView *)imageView_one{
   CGFloat h = kScreenWidth/imageView_one.image.size.width*imageView_one.image.size.height;
    return h;
    
}
+(NSString*)convertToJSONData:(id)infoDict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    
    NSString *jsonString = @"";
    
    if (! jsonData)
    {
        NSLog(@"Got an error: %@", error);
    }else
    {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符
    
    [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    return jsonString;
}
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

//头像
+(NSDictionary *)return_dic{
    
    NSUserDefaults *defult =  [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = [defult objectForKey:@"userList"];
    
    return dic;
    
}

//用户id
+(NSDictionary *)return_dic_name{
    NSUserDefaults *defult =  [NSUserDefaults standardUserDefaults];
    
    NSDictionary *dic = [defult objectForKey:@"userNameList"];
    
    return dic;
    //17085375010
}

//备注
+(NSDictionary *)return_remark_name{
    NSUserDefaults *defult =  [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = [defult objectForKey:@"remarkList"];
    return dic;
}

+ (BOOL)isValidateMobile:(NSString *)mobile{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if (mobile.length != 11)
    {
        return NO;
        
    }else{
        
        /**
         
         * 移动号段正则表达式
         
         */
        
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        
        /**
         
         * 联通号段正则表达式
         
         */
        
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(170[8-9])\\d{7}$";
        
        /**
         
         * 电信号段正则表达式
         
         */
        
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
            
        }else{
            return NO;

        }
        
    }
}



+ (NSString*)dayStringFromDate{
    
    NSDate *inputDate = [NSDate date];
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [calendar setTimeZone: timeZone];
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    NSString *week = [weekdays objectAtIndex:theComponents.weekday];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy年MM月dd日";
    NSString *time = [formatter stringFromDate:inputDate];
    
    return [NSString stringWithFormat:@"%@ %@",week,time];
    
}

@end
